<template>
  <div class="uploadImage">
    <h3>测试图片压缩</h3>
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      accept="image/*"
      :show-file-list="false"
      :before-upload="beforeUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <div>压缩前{{beforeCompression}}KB</div>
    <div>压缩后{{afterCompression}}KB</div>
  </div>
</template>
<script>
export default {
  name: 'UploadImage',
  data() {
    return {
      imageUrl: null,
      beforeCompression: 0,
      afterCompression: 0,
    }
  },
  methods: {
    beforeUpload(file) {
      console.log('file', file)
      this.beforeCompression = (file.size / 1024).toFixed(2)
      // 压缩图片
      let quantity = 1
      if (file.size >= 3 * 1024 * 1024) {
        quantity = 0.5
      } else if (file.size > 1024 * 1024) {
        quantity = 0.8
      } else {
        quantity = 1
      }
      let lrz = require('lrz')
      let url = window.URL.createObjectURL(file, { quality: 0 })
      console.log('url',url)
      lrz(url, { quantity: quantity }).then((res) => {
        console.log('res', res)
        this.afterCompression = (res.file.size / 1024).toFixed(2)
      })
    },
  },
}
</script>
<style lang="less" scoped>
::v-deep {
  .avatar-uploader {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      margin: 10px 0px;
      &:hover {
        border-color: #409eff;
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
